import Router from 'koa-router';
import passport from 'koa-passport';
import { getHash } from '../utils';
import { getUserByUserAndPass, getUserById, getToken, removeToken, createToken } from '../models';
import { isLocalAuthenticated ,isBearerAuthenticated } from '../auth';

const router = new Router();

router.post('/token', async (ctx, next) => {
	return passport.authenticate('local', async function(err, user, info, status) {

	    if (user === false) {
	      	ctx.body = { status:0, info:'登陆失败', data:null}
	    } else {
	      	await removeToken(user.userId);
	      	ctx.body = { status:1,info:'',data:{
	      		accessToken:await createToken({
		      		token:getHash((Math.random() * 100).toString()) + 'daddy',
		      		userId:user.userId
		      	}),
		      	user:user
	      	}}
	    }
	})(ctx, next)
});

router.get('/token', 
	isBearerAuthenticated(),
	async (ctx, next)=>{
		const token = ctx.request.header.authorization.split(" ")[1];
		const accessToken = await getToken(token);
		ctx.body = { 
			status:1,
			info:'',
			data:await getUserById(accessToken.userId)
		}
	}
);

export default router.routes();